package com.csit.action;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.csit.entity.CustomerCard;
import com.csit.service.CustomerCardService;
import com.csit.util.ResponseMsgUtil;
import com.csit.util.StringUtil;
import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("basePackage")
@Action("card")
public class CustomerCardAction extends BaseAction implements ModelDriven<CustomerCard> {

	private static final long serialVersionUID = -8629569572385299695L;

	private CustomerCard card = new CustomerCard();
	
	@Resource
	private CustomerCardService cardService;
	
	public CustomerCard getModel() {
		return card;
	}
	
	public void add(){
		ResponseMsgUtil msgUtil = new ResponseMsgUtil(false);
		if(StringUtil.isNull(card.getCardCode())){
			msgUtil.setMsg("卡号不能为空");
			ajaxJson(msgUtil.toJSON());
			return;
		}
		if(card.getCustomer()==null){
			msgUtil.setMsg("客户不能为空");
			ajaxJson(msgUtil.toJSON());
			return;
		}
		
		if(cardService.isEntityExist("cardCode", card.getCardCode())){
			msgUtil.setMsg("该卡号已存在,请重新输入");
			ajaxJson(msgUtil.toJSON());
			return;
		}
		if(card.getAmount()==null){
			card.setAmount(0d);
		}
		if(card.getScore()==null){
			card.setScore(0);
		}
		cardService.saveEntity(card);
		msgUtil.setSuccess(true);
		ajaxJson(msgUtil.toJSON());
	}
	
	public void update(){
		ResponseMsgUtil msgUtil = new ResponseMsgUtil(false);
		if(StringUtil.isNull(card.getCardCode())){
			msgUtil.setMsg("卡号不能为空");
			ajaxJson(msgUtil.toJSON());
			return;
		}
		if(card.getCustomer()==null){
			msgUtil.setMsg("客户不能为空");
			ajaxJson(msgUtil.toJSON());
			return;
		}
		String oldValue = cardService.getEntity("customer", card.getCustomer()).getCardCode();
		
		if(!cardService.isEntityUnique("cardCode", oldValue, card.getCardCode())){
			msgUtil.setMsg("该卡号已存在,请重新输入");
			ajaxJson(msgUtil.toJSON());
			return;
		}
		if(card.getAmount()==null){
			card.setAmount(0d);
		}
		if(card.getScore()==null){
			card.setScore(0);
		}
		cardService.updateEntity(card);
		msgUtil.setSuccess(true);
		ajaxJson(msgUtil.toJSON());
	}
	
	public void get(){
		ResponseMsgUtil msgUtil = new ResponseMsgUtil(true);
		card = cardService.getCustomerCard(card.getCustomer());
		if(card==null){
			ajaxJson(msgUtil.toJSON());
			return;
		}
		msgUtil.setProperty("cardID", card.getCardID());
		msgUtil.setProperty("cardCode", card.getCardCode());
		msgUtil.setProperty("amount", card.getAmount());
		msgUtil.setProperty("score", card.getScore());
		msgUtil.setProperty("note", card.getNote());
		ajaxJson(msgUtil.toJSON());
	}

}
